package com.bruce.pattern.behavioral.interpreter;

import java.util.Stack;

/**
 * Created by bruce on 2018/11/10 18:41
 */
public class CalculatorExpressionParser {

    public Node parse(String statement) {
        Node left;
        Node right;
        String[] items = statement.split(" ");
        Stack<Node> stack = new Stack<>();
        for (int i = 0; i < items.length; i++) {
            switch (items[i]) {
                case "*":
                    left = stack.pop();
                    right = new ValueNode(Integer.parseInt(items[++i]));
                    stack.push(new MulNode(left, right));
                    break;
                case "/":
                    left = stack.pop();
                    right = new ValueNode(Integer.parseInt(items[++i]));
                    stack.push(new DivNode(left, right));
                    break;
                case "%":
                    left = stack.pop();
                    right = new ValueNode(Integer.parseInt(items[++i]));
                    stack.push(new ModNode(left, right));
                    break;
                default:
                    stack.push(new ValueNode(Integer.parseInt(items[i])));
                    break;
            }
        }
        return stack.pop();
    }


}
